<?php

use p5\objects\CharsetUtils;
use p5\objects\JsUtils;

function mget($matrix, $key, $defaultValue = "", $safeReplace = true)
{
    $value = $defaultValue;
    if (is_array($matrix) && array_key_exists($key, $matrix)) {
        $value = $matrix[$key];
    }
    if ($safeReplace) {
        return value_replace($value);
    }
    return $value;
}

function fill_blank(&$matrix, $key, $value)
{
    if (!array_key_exists($key, $matrix) || empty($matrix[$key])) {
        $matrix[$key] = $value;
    }
}

function fill_blank_from_request(&$matrix, $keys = array())
{
    if (empty($keys)) {
        $keys = array_keys(get_parameters());
    }
    for ($i = 0; $i < count($keys); $i++) {
        fill_blank($matrix, $keys[$i], get($keys[$i]));
    }
}

function array_mirror(&$m1, $m2)
{
    $keys = array_keys($m1);
    for ($i = 0; $i < count($keys); $i++) {
        $key = $keys[$i];
        if (array_key_exists($key, $m2)) {
            $m1[$key] = $m2[$key];
        }
    }
    return $m1;
}

function get_nearby_elements($matrix, $element, $position)
{
    if (empty($matrix)) {
        return "";
    }
    $size = count($matrix);
    $offset = 0;
    for ($i = 0; $i < $size; $i++) {
        if ($matrix[$i] == $element) {
            $offset = $i + $position;
            $offset = max($offset, 0);
            $offset = $offset % $size;
            break;
        }
    }
    return $matrix[$offset];
}

function format_percent($num)
{
    if (empty($num)) {
        return "0.00%";
    }

    $num = round($num * 100, 2);
    if (strpos($num, ".") == false) {
        $num = $num . ".00";
    } else {
        $num = $num . "00";
        $index = strpos($num, ".");
        $num = substr($num, 0, $index + 3);
    }
    return $num . " %";
}

function get_unique_id($len)
{
    $string = (time() - 1250000000) . "";
    while (strlen($string) < $len) {
        $string .= rand(0, 9);
    }
    return $string;
}

function random_string($len)
{
    $i = 0;
    $str = "";
    while ($i < $len) {
        $str .= chr((rand() % 26) + 97);
        $i++;
    }
    return $str;
}


function map_replace($str, $matrix)
{
    while (list($key, $value) = each($matrix)) {
        $str = str_replace($key, $value, $str);
    }
    return $str;
}

function to_int($object)
{
    if (is_array($object)) {
        return to_int_array($object);
    }
    return $object * 1;
}

function to_int_array($matrix)
{
    $size = count($matrix);
    while (list($key, $value) = each($matrix)) {
        $matrix[$key] = $value * 1;
    }
    return $matrix;
}

function to_array($object)
{
    if (is_array($object)) {
        return $object;
    }
    return array($object);
}

function first_not_empty_value($matrix, $keys = array())
{
    for ($i = 0; $i < count($keys); $i++) {
        $key = $keys[$i];
        if (!array_key_exists($key, $matrix)) {
            continue;
        }
        if (!empty($matrix[$key])) {
            return $matrix[$key];
        }
    }
    return "";
}

function to_utf8_name($encode)
{
    return CharsetUtils::to_utf8_name($encode);
}


function is_email($address)
{
    return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
}

/*
function is_integer($v){
	return preg_match("/^(\d+)$/",$v) > 0 ;
}
*/

/**
 * @param $word
 * @return mixed|string
 */
function get_unicode_from_one_utf8($word)
{
    return CharsetUtils::get_unicode_from_one_utf8($word);
}

function be_division($a, $b, $n, $p)
{
    if ($b == 0) {
        return 0 . ($p ? " %" : "");
    }

    $c = $a * 1.0 / $b;
    if ($p) {
        return number_format($c * 100, $n) . " %";
    }
    return number_format($c, $n);
}

function load_properties($file, $encode)
{
    $content = file_get_contents($file);
    $content = str_replace("\r\n", "\n", $content);
    $lines = explode("\n", $content);
    $table = array();
    for ($i = 0; $i < count($lines); $i++) {
        $line = $lines[$i];
        $pos = strpos($line, "=");
        if ($pos != false) {
            $key = trim(substr($line, 0, $pos));
            $value = trim(substr($line, $pos + 1));
            $table[$key] = $value;
        }
    }
    return $table;
}


function absolutly_basename($filename)
{
    $name = basename($filename);
    $temp = explode("?", $name);
    return $temp[0];
}

function get_php_encoding()
{
    return "utf-8";
}

function get_os_encoding()
{
    return CharsetUtils::get_os_encoding();
}

function to_os_encoding($string)
{
    return CharsetUtils::to_os_encoding($string);
}

function to_php_encoding($string)
{
    return CharsetUtils::to_php_encoding($string);
}

function string_index($string, $separator, $beginPos, $endPos)
{
    $tag = explode($separator, $string);
    $result = array_slice($tag, $beginPos, $endPos);
    $return_value = "";
    $i = 0;
    foreach ($result as $value) {
        if ($i > 0) {
            $return_value .= $separator;
        }
        $return_value .= $value;
        $i++;
    }
    return $return_value;
}

function round_pad_zero($num, $precision)
{
    if ($precision < 1) {
        return round($num, 0);
    }
    $r_num = round($num, $precision);
    $num_arr = explode('.', $r_num);
    if (count($num_arr) == 1) {
        return $r_num . '.' . str_repeat('0', $precision);
    }
    $point_str = "$num_arr[1]";
    if (strlen($point_str) < $precision) {
        $point_str = str_pad($point_str, $precision, '0');
    }
    return $num_arr[0] . '.' . $point_str;
}

function is_ip($ip)
{
    $temp = explode(".", $ip);
    $result = false;
    if (count($temp) > 4) {
        $result = false;
    } else {
        for ($i = 0; $i < 4; $i++) {
            $val = intval($temp[$i]);
            if ($i == 0) {
                if ($val > 0 && $val < 256) {
                    $result = true;
                } else {
                    $result = false;
                    break;
                }
            } else {
                if ($val >= 0 && $val < 256) {
                    $result = true;
                } else {
                    $result = false;
                    break;
                }
            }
        }
    }
    return $result;
}


function find_elements_with_key_prefix($matrix, $key_prefix)
{
    $temp = array();
    $keys = array_keys($matrix);
    for ($i = 0; $i < count($keys); $i++) {
        $key = $keys[$i];
        if (substr($key, 0, strlen($key_prefix)) == $key_prefix) {
            $temp[$key] = $matrix[$key];
        }
    }
    return $temp;
}

$print_html_index = 0;
function print_html($string)
{
    global $print_html_index;
    if (is_json_response()) {
        return;
    }
    if (is_text_response()) {
        print "\r\n" . ($print_html_index++) . " [" . current_time() . "] : " . $string;
    } else {
        print "<br>" . ($print_html_index++) . " [" . current_time() . "] : " . $string;
    }
}

function print_text($string)
{
    print_html($string);
}

function js_debug($string, $result = true)
{
    global $configs;
    if ($configs["product_mode"] == false && $result == false) {
        $id = random_string(8);
        print "<textarea id='$id'>$string</textarea>";
        JsUtils::do_every("alert(document.getElementById('$id').value);");
    }
}

function is_json_response()
{
    return check_mime_type("application/json");
}

function is_text_response()
{
    return check_mime_type("text/plian");
}

function check_mime_type($type)
{
    $headers = headers_list();
    for ($i = 0; $i < count($headers); $i++) {
        $header = strtolower($headers[$i]);
        if (strpos($header, $type) != false) {
            return true;
        }
    }
    return false;
}

function filter_empty_elements($matrix)
{
    $temp = array();
    for ($i = 0; $i < count($matrix); $i++) {
        $e = $matrix[$i];
        if (!empty($e)) {
            array_push($temp, $e);
        }
    }
    return $temp;
}